import React, { Component } from 'react'
import { connect } from 'react-redux'
import moment from 'moment'
import _ from 'underscore'
import { Tag, Button, Form, Input, InputNumber, Icon, Cascader, Select, AutoComplete, Spin, Modal } from 'antd';
import SearchSelect from 'react-select';
import 'react-select/dist/react-select.css';

import table from '../../charts/table'
import { merge, trim, ajax } from '../../helper/helper'
import { ContentHeader } from '../../wrapper'
import NewContact from './newContact';
import { actions } from '../action/action'
import Profile from '../../common/profile-for-table'
import { socialListTh, timeFilter, socialStatus, optionsList, subList1, subList2, profileList, userAttribute, } from '../static/index'
import ReactDropDown, { ReactDropDownFull, DropDownLevel, DropDownMultiLevel } from './dropdown'
import AttributeDropdown from '../../common/userprofilefilter';
import { tagsColor } from '../static/index';

const FormItem = Form.Item;
const Option = Select.Option;


const attributeOption = {
    profileList: profileList,
    userAttribute: userAttribute
};
let socialListOptions = {
    title: '客户列表',
    limit: 6,
    maxPageCount: 50,
    thead: socialListTh,
    pagebar: true,
    download: false,
    search: 'customerName',
    placeholder: '请输入用户名称',
    setting: '#/CRMReport?listSetting=true',
    beforeRender: function (data, options) {
        return [
            <Profile
                data={{ id: data.customerId, headImage: data.headImage, name: data.customerName }}
                options={{
                    route: '#detail?userID='
                }}
            />,
            <Gender data={data} />,
            <PhoneNumber data={data} />,
            <Color data={data} />,
            <Size data={data} />,
            <Tags data={data} />,
            <Address data={data} />,
            // <Email data={data} />,
            <SubscribeTime data={data} />,
        ]
    },
    trigger: ['type']
};

const _Profile = connect(
    state => {
        return {

        }
    },
    dispatch => {
        return {
            setCurrentVisit: (data) => {
                dispatch({
                    type: 'set-visit-data',
                    val: data
                });
            }
        }
    }
)(Profile);

class CRMReport extends Component {
    componentWillMount() {
        let pathname = location.pathname;
        if (pathname == '/users/') {
            this.props.setCurrentType('distinct');
        } else if (pathname == '/users/snap') {
            this.props.setCurrentType('snap');
        } else {
            this.props.setCurrentType('vip');
        }

        let self = this;
        this.props.clearEventListData();
        // this.time = setInterval(() => {
        //     self.props.getVisit(self.props.getVisitTime);
        // }, 2000);
    }
    // componentWillUnmount() {
    //     clearInterval(this.time);
    // }

    redirectUserCenterDetail(data) {
        this.props.closeCenterPopup();
        this.props.setCurrentVisit(data);
        location.href = `#/detail?userID=${data.customerId}`;
    }
    redirectUserBottomDetail(data) {
        this.props.setCurrentVisit(data);
        location.href = `#/detail?userID=${data.customerId}`;
    }


    render() {
        const { location, visits, visitPage, setVisitPage, isHideCenterPopup, closeCenterPopup, isHideBottomPopup, closeBottomPopup, keyword, changeKeyword, isAddContact, triggerNewContact } = this.props;
        const redirectUserCenterDetail = this.redirectUserCenterDetail.bind(this);
        const redirectUserBottomDetail = this.redirectUserBottomDetail.bind(this);
        const status = location.query.status;
        const listSetting = location.query.listSetting ? true : false;
        var start = (visitPage - 1) * 12, end = visitPage * 12 > visits.length ? visits.length : visitPage * 12;
        var arr = visits.slice(start, end);
        let visible1 = visits && visits.length > 0 && !isHideCenterPopup || isHideBottomPopup && visits.length > 0;
        let pathname = window.location.pathname;
        let title = pathname == '/users/snap' ? '到店顾客' : 'VIP客户列表';

        return <div className="userList">
            {/* <div className="center_layer">
                <Modal complete={true} title="来电顾客" submitText="查看客户详细" data={visits[0]} onClose={closeCenterPopup} onSubmit={redirectUserCenterDetail(visits[0])} >
                    <img style={{ width: '150px', height: '150px', marginBottom: '15px', cursor: 'pointer' }} src={visits.length > 0 ? `http://120.27.20.74:8080/face/pic/${visits[0].headImage}.jpg` : ''} />
                    <p>{visits.length > 0 ? visits[0].customerName : ''}</p>
                </Modal>

            </div> */}
            {
                visible1 ?
                    <div className="center_layer">
                        <Modal visible={true} title="来电顾客" onCancel={closeCenterPopup} footer={[
                            <Button key="back" size="large" onClick={closeCenterPopup}>关闭</Button>,
                            <Button key="submit" type="primary" size="large" onClick={() => redirectUserCenterDetail(visits[0])}>
                                接待顾客
                        </Button>
                        ]}>
                            <div style={{ float: 'left', marginRight: 10, width: 100, height: 100, borderRadius: '50%', backgroundImage: `url(http://47.104.2.156/${visits.length ? visits[0].headImage : ''})`, backgroundSize: 'cover' }}></div>
                            <p>姓名：{visits[0].customerName}</p>
                            <p>性别：{visits[0].gender}</p>
                            <p>标签：{visits[0].tags}</p>
                            <p>偏爱颜色：{visits[0].colorName}</p>
                            <p>尺码：{visits[0].sizeName}</p>


                        </Modal>
                    </div>
                    : ''

            }
            {
                visits.length > 1 && !isHideBottomPopup ?
                    <div className="bottom_layer">
                        <div className="modal-header">
                            <button type="button" className="close" onClick={closeBottomPopup}><span>&times;</span></button>
                            <h4 className="modal-title">访店顾客</h4>
                        </div>
                        <div className="wait-customer">
                            {
                                visitPage == 1 ?
                                    ''
                                    :
                                    <span className="fa fa-angle-left fa-lg" onClick={() => setVisitPage(visitPage - 1)}></span>
                            }
                            {
                                arr.map((v, index) => {
                                    return <img onClick={() => redirectUserBottomDetail(v)} src={visits.length > 0 ? `http://47.104.2.156/${v.headImage}` : ''} key={index} style={{ cursor: 'pointer' }} />
                                })
                            }
                            {
                                visitPage * 12 >= visits.length ?
                                    ''
                                    :
                                    <span className="fa fa-angle-right fa-lg" onClick={() => setVisitPage(visitPage + 1)}></span>

                            }
                        </div>
                    </div>
                    : ''
            }
            {/* <section className="content-header">
                <h1>
                    客户管理
                </h1>
                <div className="breadcrumb">
                    {/* <div className="search">
                        <input type="text" value={keyword} onChange={changeKeyword} />
                        <i className="fa fa-search"></i>
                    </div>}
                    <button className="btn btn-primary">新增客户</button>
                </div>
            </section> */}
            <ContentHeader title={title} icon="groups" sprite="standard-sprite" iconClassName="slds-icon-standard-contact-list" subtitle="">
                <Button type="primary" icon="plus" onClick={triggerNewContact}>新增客户</Button>
            </ContentHeader>
            <div className="content">
                {/*<_AttributeContainer />
                <_ButtonList />*/}
                <div className="row">
                    <div className="col-md-2">
                        <div className="filter">
                            <Filter />
                        </div>
                    </div>
                    <div className="col-md-10">
                        <div className="content-body">
                            <SocialList options={socialListOptions} location={location} />
                        </div>
                    </div>
                </div>


            </div>
            <Modal title="表格设置" visible={listSetting} onCancel={() => history.back()} footer={null} footer={[
                <Button key="back" type="primary" size="large" onClick={() => history.back()}>
                    关闭
                </Button>,
            ]} >
                <_PostListSetting />
            </Modal>
            {
                isAddContact ?
                    <NewContact triggerNewContact={triggerNewContact} />
                    : ''
            }

        </div >
    }
}

var _CRMReport = connect(
    function (state) {
        return {
            visits: state.visits,
            visitPage: state.visitPage,
            isHideCenterPopup: state.isHideCenterPopup,
            isHideBottomPopup: state.isHideBottomPopup,
            getVisitTime: state.getVisitTime,
            keyword: state.socialList.keyword,
            isAddContact: state.newContact.isAddContact
        }
    },
    function (dispatch) {
        return {
            setCurrentType: (type) => {
                dispatch({
                    type: 'set-cur-type',
                    val: type
                });
            },
            getVisit: (time) => {
                actions.getVisit(dispatch, time);
            },
            setGetVisitTime: (time) => {
                dispatch({
                    type: 'set-get-visit-time',
                    val: time
                });
            },
            setVisitPage: (params) => {
                dispatch({
                    type: 'set-visit-page',
                    val: params
                });
            },
            closeCenterPopup: () => {
                dispatch({
                    type: 'hide-center-popup'
                });
            },
            closeBottomPopup: () => {
                dispatch({
                    type: 'hide-bottom-popup'
                });
            },
            changeKeyword: (e) => {
                var keyword = e.target.value;
                dispatch({
                    type: 'change-keyword',
                    val: keyword
                });
            },
            setCurrentVisit: (data) => {
                dispatch({
                    type: 'set-visit-data',
                    val: data
                });
            },
            clearEventListData: () => {
                dispatch({
                    type: 'clear-event-list-data'
                });
            },
            triggerNewContact: () => {
                dispatch({
                    type: 'trigger-new-contact'
                });
            },

        }
    }
)(CRMReport);


const _ContentHeader = connect(
    function (state) {
        return {
            socialAccount: state.socialAccount
        }
    }
)(ContentHeader)

class Filter extends Component {

    callback() {

    }

    render() {
        var callback = this.callback.bind(this);
        return (
            <div className="filter-content">
                <h5>视图</h5>
                <OptionsSelector list={[{ name: '所有客户' }, { name: '我的客户' }]} callback={callback} />
                <p style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid #43a6a5' }}>
                    <a href="#">
                        <i className="fa fa-plus"></i>
                        添加过滤条件
                    </a>
                </p>
            </div>
        );
    }
}


class PostListSetting extends Component {
    render() {
        const { options, chosen, onChange } = this.props;

        return <div className="modal-body">
            {options.map((i, index) => {
                const isChecked = _.contains(chosen, index);
                return <label key={index} style={{ marginRight: 20 }}>
                    <input type="checkbox" checked={isChecked} onChange={() => onChange(isChecked ? _.without(chosen, index) : _.union(chosen, [index]))} /> {i.name}
                </label>
            })}
        </div>
    }
}


//绑定状态到发送列表
const SocialList = connect(
    function (state) {
        return state.socialList
    },
    function (dispatch) {
        return {
            getData: (params) => {
                actions.socialListSetPageIndex(dispatch, params);
                actions.socialListRenderData(dispatch, params);
                actions.socialListRequest(dispatch, params);
            },
            //左侧勾选框
            // onCheck: (params) => {
            //     actions.socialListSetOnCheck(dispatch, params);
            // }
        }
    }
)(table);


const _PostListSetting = connect(
    function (state) {
        return {
            options: socialListTh,
            chosen: state.socialList.chosen
        }
    },
    function (dispatch) {
        return {
            onChange: (order) => dispatch({
                type: 'social-list-set-chosen',
                val: _.sortBy(order)
            })
        }
    }
)(PostListSetting)

//性别
class Gender extends Component {
    render() {
        const gender = this.props.data.gender;
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{gender}</p>
        </div>
    }
}

//联系地址
class Address extends Component {
    render() {
        const address = this.props.data.address;

        return <div className="preview-media-limit preview-media-limit-group">
            <p>{address} </p>
        </div>
    }
}


//电话号码
class PhoneNumber extends Component {
    render() {
        const mobile = this.props.data.mobile;
        return <div className="preview-media-limit preview-media-limit-group">
            <p> {mobile} </p>
        </div>
    }
}


//标签
class Email extends Component {
    render() {
        const email = this.props.data.email;
        return <div className="preview-media-limit preview-media-limit-group">
            <p> {email} </p>
        </div>
    }
}

// 颜色
class Color extends Component {
    render() {
        const colorName = this.props.data.colorName;
        return <div className="preview-media-limit preview-media-limit-group">
            <p> {colorName} </p>
        </div>
    }
}

// 尺码
class Size extends Component {
    render() {
        const sizeName = this.props.data.sizeName;
        return <div className="preview-media-limit preview-media-limit-group">
            <p> {sizeName} </p>
        </div>
    }
}

// 标签
class Tags extends Component {
    render() {
        const tags = this.props.data.tags;
        const tagList = (tags == "" ? [] : tags.split('^'));
        return <div className="preview-media-limit preview-media-limit-group">
            {
                tagList.length ? tagList.map((item, index) => {
                    return <Tag key={index} color={tagsColor[index]}>{item}</Tag>
                })
                    : ''
            }
        </div>
    }
}

//单个标签
class LabelCard extends Component {
    render() {
        const tag = this.props.data;
        return <span className="badge bg-light-blue addNewTag" id={tag.id}>
            {tag.name}
            {/*<i className="fa fa-remove" ></i>*/}
        </span>
    }
}

//分组
class Group extends Component {
    render() {
        const group = this.props.data[7] || {};
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{group}</p>
        </div>
    }
}

//订阅时间
class SubscribeTime extends Component {
    render() {
        const createTimestamp = this.props.data.createTimestamp;
        return <div className="preview-media-limit preview-media-limit-group">
            <p>{createTimestamp}</p>
        </div>
    }
}

export default _CRMReport;




class ButtonList extends Component {
    render() {
        const { checked } = this.props;
        return <div className="content-body">
            <div className="btn btn-default">导出数据</div>
            {
                checked.length ? <OptionsSelector /> : ""
            }
        </div>
    }
}

const _ButtonList = connect(
    function (state) {
        return {
            checked: state.socialList.checked,
            data: state.socialList.data
        }
    },
    function (dispatch) {
        return {

        }
    }
)(ButtonList)

//================================下拉菜单=========================================

class Selector extends ReactDropDownFull {
    render() {
        const { isOpen } = this.state;
        const trigger = this.trigger.bind(this);
        const { callback, list } = this.props;
        return <div className="dropdown" ref="parent" style={{ display: 'inline-block' }}>
            <a href="javascript:void(0)" className="btn btn-default dropdown-toggle" onClick={() => this.trigger()}>选项<span className="caret"></span></a>
            {isOpen ? <div className="tags-input-list-wrapper" onClick={() => this.close()}>
                <DropDownLevel target={this.refs.parent} trigger={trigger} data={list} callback={callback} />
            </div> : ""}
        </div>
    }
}

const OptionsSelector = connect(
    function (state) {
        return merge(state.selector, {
            list: [{ name: '所有客户' }, { name: '我的客户' }]
        })
    },
    function (dispatch) {
        return {
            callback: (index, menuId) => {
                console.log('callback worked!!!!')
                actions.optionsRun(dispatch, menuId);
            },
            setMenuId: (params) => {
                dispatch({
                    type: 'set-menu-id',
                    var: params
                })
            }
        }
    }
)(Selector)


const _AttributeDropdown = connect(
    function (state) {
        return {
            attributeList: state.attributeList
        };
    },
    function (dispatch) {
        return {
            callback: (params) => {
                dispatch({
                    type: 'CHANGE_ATTRIBUTE',
                    val: params
                });
            },
            deleteAttribute: (params) => {
                dispatch({
                    type: 'DELETE_ATTRIBUTE',
                    val: params
                });
            },
            addProfile: (params) => {
                dispatch({
                    type: 'CHANGE_ADD_ATTR'
                });
            },

        };
    }
)(AttributeDropdown);

class AttributeContainer extends Component {
    render() {
        const { isAddProfile, addProfile } = this.props;
        return <div className="row">
            <div className="col-sm-12">
                <div className="box box-solid">
                    {
                        isAddProfile ?
                            <div className="box-header with-border">
                                <div className="header-attr">
                                    <i className="fa fa-user fa-lg"></i>
                                    <span className="attr-title">用户属性</span>
                                </div>
                            </div>
                            : ''
                    }
                    <div className="box-body behavior-tip">
                        {
                            isAddProfile ?
                                <_AttributeDropdown option={attributeOption} />
                                : <div>
                                    <h3 className="tip-title">
                                        <i className="fa fa-user fa-lg"></i>
                                        <strong> 用户属性 </strong>
                                        通过设置用户属性条件来筛选出特定用户
                                                </h3>
                                    <button className="btn btn-primary add-behavior" onClick={() => { addProfile(true); }}>
                                        <i className="fa fa-plus "></i>
                                        添加用户属性条件
                                </button>
                                </div>
                        }

                    </div>
                </div>
            </div>
        </div>
    }
}

const _AttributeContainer = connect(
    function (state) {
        return {
            isAddProfile: state.isAddProfile,
        }
    },
    function (dispatch) {
        return {
            addProfile: (params) => {
                dispatch({
                    type: 'CHANGE_ADD_ATTR'
                })
            }
        }
    }
)(AttributeContainer)

/*class DropDownLevel extends Component {
    constructor() {
        super()

        this.state = {
            wwidth: 0,
            left: 0,
            right: 0,
            top: 0,
            bottom: 'auto',
            showMenuItem: -1,
            showSubMenuItem: -1,
        }
    }
    componentDidMount() {
        const { target } = this.props;
        const pos = target.getBoundingClientRect() || {};
        const height = Math.max(document.body.clientHeight, window.innerHeight);
        const width = document.body.clientWidth;

        this.setState({
            width: pos.width,
            left: pos.left,
            right: (width - pos.right),
            top: pos.height + pos.top,
            bottom: ((pos.height + pos.top + 64) > height ? 10 : 'auto')
        })
    }
    menuHover(index) {
        this.setState({ showMenuItem: index })
    }

    menuLeave() {
        this.setState({
            showMenuItem: -1,
            showSubMenuItem: -1
        })
        this.props.trigger();

    }

    subMenuHover(index, subIndex) {
        this.setState({
            showMenuItem: index,
            showSubMenuItem: subIndex
        })
    }

    subMenuLeave() {
        this.setState({ showSubMenuItem: -1 })
    }
    preventEvent(e) {
        e.stopPropagation();
    }
    render() {
        const { width, left, right, top, bottom } = this.state;

        let style = { display: 'block', left: left, top: top, bottom: bottom };
        let onMouseOver = this.menuHover.bind(this),
            onMouseLeave = this.menuLeave.bind(this),
            showMenuItem = this.state.showMenuItem,
            subMenuHover = this.subMenuHover.bind(this),
            subMenuLeave = this.subMenuLeave.bind(this),
            showSubMenuItem = this.state.showSubMenuItem,
            preventEvent = this.preventEvent.bind(this);
        return <div >
            <ul id="menuOptionContainer" className="dropdown-menu" style={style} onClick={(e) => { preventEvent(e) }}>
                <li onMouseOver={() => { onMouseOver(1) }}
                    className={(showMenuItem == 1) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        拷贝标签
                    </a>
                </li>
                <li onMouseOver={() => { onMouseOver(2) }}
                    className={(showMenuItem == 2) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        移动分组
                    </a>
                </li>
            </ul>
            {
                showMenuItem == 1 ?
                    <SubMenuCopyTag subMenuHover={subMenuHover} style={style} subMenuLeave={subMenuLeave} onMouseLeave={onMouseLeave} showSubMenuItem={showSubMenuItem} /> :
                    showMenuItem == 2 ?
                        <SubMenuMoveList subMenuHover={subMenuHover} style={style} subMenuLeave={subMenuLeave} onMouseLeave={onMouseLeave} showSubMenuItem={showSubMenuItem} /> : null
            }
        </div>
    }
}
class SubMenuCopyTag extends Component {
    render() {
        let style = this.props.style;
        style.left = style.left + document.getElementById('menuOptionContainer').clientWidth;
        const curStyle = style;
        const showSubMenuItem = this.props.showSubMenuItem,
            subMenuHover = this.props.subMenuHover,
            subMenuLeave = this.props.subMenuLeave,
            onMouseLeave = this.props.onMouseLeave;
        return <div onClick={onMouseLeave} onMouseLeave={subMenuLeave}>
            <ul className="dropdown-menu" style={curStyle}>
                <li onMouseOver={() => { subMenuHover(1, 1) }}
                    className={(showSubMenuItem == 1) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        标签1
                    </a>
                </li>
                <li onMouseOver={() => { subMenuHover(1, 2) }}
                    className={(showSubMenuItem == 2) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        标签2
                    </a>
                </li>
                <li onMouseOver={() => { subMenuHover(1, 3) }}
                    className={(showSubMenuItem == 3) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        标签3
                    </a>
                </li>
                <li onMouseOver={() => { subMenuHover(1, 4) }}
                    className={(showSubMenuItem == 4) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        标签4
                    </a>
                </li>
                <li onMouseOver={() => { subMenuHover(1, 5) }}
                    className={(showSubMenuItem == 5) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        标签5
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                    </a>
                </li>
            </ul>
        </div>
    }
}
class SubMenuMoveList extends Component {
    render() {
        let style = this.props.style;
        style.left = style.left + document.getElementById('menuOptionContainer').clientWidth;
        const curStyle = style;
        const showSubMenuItem = this.props.showSubMenuItem,
            subMenuHover = this.props.subMenuHover,
            subMenuLeave = this.props.subMenuLeave,
            onMouseLeave = this.props.onMouseLeave;
        return <div onClick={onMouseLeave} onMouseLeave={subMenuLeave}>
            <ul className="dropdown-menu" style={curStyle}>
                <li onMouseOver={() => { subMenuHover(2, 1) }}
                    className={(showSubMenuItem == 1) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        分组1
                    </a>
                </li>
                <li onMouseOver={() => { subMenuHover(2, 2) }}
                    className={(showSubMenuItem == 2) ? 'active' : null} >
                    <a href="javascript:void(0)">
                        <i className="fa fa-chain" style={{ width: '1.1em' }}></i>
                        分组2
                    </a>
                </li>
            </ul>
        </div>
    }
}*/
